from django.core.cache import cache
from django.http import JsonResponse
from rest_framework.views import APIView

from apps.app01 import models


class ForgetPasswordView(APIView):
    """重置密码验证码校验"""

    authentication_classes = []

    def post(self, request):
        email = request.data.get('email')
        code = request.data.get('code')
        cache_code = cache.get(email)
        if not cache_code:
            return JsonResponse({'code': 400, 'message': '验证码已失效，请重新获取'}, status=400)
        if str(cache_code) != str(code):
            return JsonResponse({'code': 401, 'message': '验证码错误，请重新输入'}, status=401)
        cache.delete(email)
        user = models.User .objects.filter(email=email).first()
        if not user:
            return JsonResponse({'code': 404, 'message': '用户不存在，请先注册'}, status=404)
        return JsonResponse({'code': 200, 'message': 'OK','data': {'id': user.id}}, status=200)